<?php

namespace app\modules\adminapi\controllers;

use app\filters\CheckAccessFilter;
use app\helpers\Coin;
use app\models\SaleRcdOther;
use app\models\User;
use yii\db\ActiveQuery;
use yii\db\Expression;

class IndexController extends BaseController
{
    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'checkAccess' => [
                'class' => CheckAccessFilter::className(),
                'checkAccess' => [$this, 'checkAccess'],
                'only' => ['configs']
            ],
        ]); // TODO: Change the autogenerated stub
    }

    public function actionIndex($show_type = 0)
    {
        switch ($show_type) {
            case 0:
                $this_where = true;
                break;//全部
            case 1:
                $this_where = 'create_time >=' . strtotime(date('Y-m-01'));
                break;//本月
            case 2:
                $this_where = 'create_time >=' . strtotime(date('Y-m-d'));
                break;//本日
            default:
                $this_where = true;//全部
        }

        $types = ['years', 'months', 'days'];

        $lastOrderCount = SaleRcdOther::find()->where($this_where)->count();

        $sevenSteps = array_column(array_map(function ($val) use ($show_type, $types) {
            $formats = ['Y', 'Y-m', 'Y-m-d'];
            $date = date($formats[$show_type], strtotime("-" . (7 - $val) . $types[$show_type]));
            return ['label' => $date, 'count' => 0];
        }, range(0, 6)), null, 'label');

        $sevenCountsFunc = function ($query, $name, $countField = 'count(*)', $eachFunction = null) use ($sevenSteps, $types, $show_type) {
            $formats = ['%Y', '%Y-%m', '%Y-%m-%d'];
            $format = $formats[$show_type];
            /** @var  $query ActiveQuery */
            $data = $query
                ->andWhere('create_time > :create_time', ['create_time' => strtotime("-7" . $types[$show_type])])
                ->groupBy('label')
                ->select(new Expression("from_unixtime(create_time, '{$format}') as label,{$countField} as count"))
                ->asArray()
                ->all();

            if ($eachFunction) {
                array_walk($data, $eachFunction);
            }

            $counts = array_values(
                array_column($data, null, 'label')
                +
                $sevenSteps);

            uasort($counts, function ($a, $b) {
                return $a['label'] == $b['label'] ? 0 : (($a['label'] < $b['label']) ? -1 : 1);
            });

            return array_values($counts);
        };

        $sevenOrderCounts = $sevenCountsFunc(SaleRcdOther::find(), 'ordercount');
        $newOrderCount = SaleRcdOther::find()->where($this_where)->andWhere([
            'and',
            ['=','status',SaleRcdOther::STATUS_WAIT_CONFIRM],
            ['=','logistics_status',SaleRcdOther::LOGISTICS_STATUS_WAIT_HANDLE]
        ])->count();

        $lastUserCount = User::find()->where($this_where)->count();
        $sevenUserCounts = $sevenCountsFunc(User::find(), 'usercount');

        $lastSupplierCount = User::find()->where($this_where)->andWhere(['=', 'type_id', User::TYPE_PEER])->count();
        $sevenSupplierCounts = $sevenCountsFunc(User::find()
            ->andWhere('type_id = :type_id', ['type_id' => User::TYPE_PEER])
            , 'suppliercount'
        );

        $lastOrderSum = round(Coin::getValueToCny(SaleRcdOther::find()->where($this_where)->sum('total_price'), Coin::UNIT_THB), 2);
        $sevenOrderSums = $sevenCountsFunc(SaleRcdOther::find(), 'ordersum', 'sum(total_price)', function (&$item, $key) {
            $item = ['label' => $item['label'], 'count' => round(Coin::getValueToCny($item['count'], Coin::UNIT_THB), 2)];
        });

        $supplierExtendsInfo = User::find()
            ->where($this_where)
            ->andWhere('type_id = :type_id', ['type_id' => User::TYPE_PEER])
            ->select('nickname,(select count(*) from '
                . 'user as g where g.parent_id = '
                . 'user.id) as city_count')
            ->orderBy('city_count desc')
            ->limit(10)
            ->asArray()
            ->all();

        $supplierSalesInfo = User::find()
            ->where($this_where)
            ->andWhere('type_id = :type_id', ['type_id' => User::TYPE_PEER])
            ->select(new Expression('nickname,(select TRUNCATE(sum(total_price),1) from '
                . 'sale_rcd_other right join '
                . 'user as g on '
                . 'sale_rcd_other.user_id = g.id where g.parent_id = '
                . 'user.id) as city_count'))
            ->orderBy('city_count desc')
            ->limit(10)
            ->asArray()
            ->all()
        ;

        $productSalesInfo = SaleRcdOther::find()
            ->limit(10)
            ->andWhere($this_where)
            ->andWhere(new Expression("product_name <> ''"))
            ->select(new Expression('product_name as label,sum(adult_num+child_num) as count'))
            ->groupBy('product_name')
            ->orderBy('count desc')
            ->asArray()
            ->all()
        ;

        return [
            'orderInfo' => [
                'newCount' => $newOrderCount,
                'lastCount' => $lastOrderCount,
                'sevenCounts' => $sevenOrderCounts,
            ],
            'userInfo' => [
                'lastCount' => $lastUserCount,
                'sevenCounts' => $sevenUserCounts,
            ],
            'supplierInfo' => [
                'lastCount' => $lastSupplierCount,
                'sevenCounts' => $sevenSupplierCounts,
            ],
            'orderSumInfo' => [
                'lastCount' => $lastOrderSum,
                'sevenCounts' => $sevenOrderSums,
            ],
            'sevenStep' => $sevenSteps,
            'supplierExtendsInfo' => $supplierExtendsInfo,
            'supplierSalesInfo' => $supplierSalesInfo,
            'productSalesInfo' => $productSalesInfo,
        ];
    }
}
